//
//  GardenLoveViewController.m
//  TrueLove
//
//  Created by han on 15-1-28.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "GardenLoveViewController.h"
#import "GardenCell.h"
#import "AFHTTPRequestOperationManager.h"
#import "workTeam.h"
#import "UIImageView+WebCache.h"
#import "DetalisViewController.h"
#import "PicViewController.h"
#import "UIButton+WebCache.h"
#import "MBProgressHUD.h"
#import "WebViewController.h"
@interface GardenLoveViewController ()

@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)UIPageControl *pageControl;
@property (nonatomic, retain)UIScrollView *scrollView;
@property (nonatomic, retain)NSMutableArray *imageArr;// 装轮播图片
@property (nonatomic, retain)NSMutableArray *urlArr;  //装解析数据的数组
@property (nonatomic, retain)NSMutableArray *picArr;  // 装首页轮播
@property (nonatomic, retain)MBProgressHUD *progress;
@end

@implementation GardenLoveViewController
- (void)dealloc
{
    [_scrollView release];
    [_tableView release];
    [_pageControl release];
    [_imageArr release];
    [super dealloc];
}

// 在头 加一张图片(最后一张) 在尾部加一张(第一张)

//- (void)handleImages
//{
//    id imageFirst = [self.imageArr firstObject];
//    id imageLast = [self.imageArr lastObject];
//    
//    [self.imageArr insertObject:imageLast atIndex:0];
//    [self.imageArr addObject:imageFirst];
//    [self getImageUrl];
//    
//    
//}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = NO;
    self.title = @"爱之院";
   // [self createTableView];
    //
    [self createPageControl];
    //NSLog(@"%ld",self.imageArr.count);
    
    [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(runTimePage) userInfo:nil repeats:YES];
    [self getImageUrl];
    [self getUrl];

}
// 解析数据(下面的工作室)
- (void)getUrl
{
    NSString *str = @"http://www.hunliji.com/v2/api/app/works?per_page=20&first_query_time=2015-01-26T03:39:27Z&page=1";
    
    self.urlArr = [NSMutableArray array];
    
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    [manger GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSMutableArray *arr = [responseObject objectForKey:@"works"];
       // NSLog(@"====%@",arr);
        for (NSDictionary *dic in arr) {
            workTeam *team = [[workTeam alloc] init];
            [team setValuesForKeysWithDictionary:dic];
            [self.urlArr addObject:team];
            [team release];
            
        }
     
       
        
        [self createTableView];
        [self.progress hide:YES];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);
    }];
    
}

// 解析轮播 图片
- (void)getImageUrl
{
    NSString *picStr = @"http://www.hunliji.com/v2/api/app/banners.json?site=7&city=0";
    self.picArr = [NSMutableArray array];
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    manger.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];

    [manger GET:picStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        self.picArr = responseObject;
        NSLog(@"%@", self.picArr);
        [self createImage];
        [self createTableView];
        [self runTimePage];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
    }];
    
    
}





- (void)runTimePage
{
    NSInteger page = self.pageControl.currentPage;
    page ++;
    
    page = page > self.picArr.count - 1 ? 0: page;
    self.pageControl.currentPage = page;
    [self changePage:self.pageControl];
    
    
}


- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    self.scrollView.backgroundColor = [UIColor redColor];
    
   
    self.scrollView.contentSize = CGSizeMake(self.picArr.count *self.view.frame.size.width, 0);
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    self.scrollView.contentOffset = CGPointMake(0, 0);
    self.tableView.tableHeaderView = self.scrollView;
    [self createImage];
    [self createPageControl];
    // 加一个小菊花
   self.progress = [[MBProgressHUD alloc] initWithView:self.view];
   self.progress.mode = MBProgressHUDModeText;
    self.progress.labelText = @"稍等";
    self.progress.margin = 10 ;
    self.progress.yOffset = 50;
    self.progress.removeFromSuperViewOnHide = YES;
    [self.progress show:YES];
    [self.view addSubview:self.progress];
    [_progress release];
    
    
    
    [_scrollView release];
    
    [_tableView release];
    
}

- (void)createPageControl
{
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(140, 170, 100, 30)];
    self.pageControl.numberOfPages = self.picArr.count;
    self.pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    self.pageControl.pageIndicatorTintColor = [UIColor whiteColor];
    [self.tableView addSubview:self.pageControl];
    [self.pageControl addTarget:self action:@selector(changePage:) forControlEvents:UIControlEventValueChanged];
    [_pageControl release];

    
    
}
// 点击pageControl的方法
- (void)changePage:(UIPageControl *)page
{
    [self.scrollView setContentOffset:CGPointMake(page.currentPage*self.scrollView.frame.size.width, 0) animated:YES];
    
}

// 循环滚动

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    if (self.scrollView.contentOffset.x >= self.scrollView.frame.size.width *(self.picArr.count-1)) {
        
        [self.scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
    }
    if (self.scrollView.contentOffset.x <= -10) {
        [self.scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width *(self.picArr.count-1), 0)  animated:NO];
    }
    
    
}

// 使页面的变化和pageControl变化一致
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
        self.pageControl.currentPage = (self.scrollView.contentOffset.x) / (self.scrollView.frame.size.width) ;
    
}






// 添加首页轮播

- (void)createImage
{
    
    
    for (int i = 0; i < self.picArr.count; i ++) {
        
        NSString *name = [[self.picArr objectAtIndex:i] objectForKey:@"image_path"];
        
       // UIImageView *image = [[UIImageView alloc] initWithImage:[self.imageArr objectAtIndex:i]];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.tag = 10 + i;
        
        button.frame = CGRectMake(i * self.view.frame.size.width, 0, self.view.frame.size.width, self.scrollView.frame.size.height);
        
        NSURL *url = [NSURL URLWithString:name];
        //[image setImageWithURL:url];
        [button setBackgroundImageWithURL:url forState:UIControlStateNormal];
        button.backgroundColor = [UIColor grayColor];
        [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:button];
        
        
        
        
        
        }
}

- (void)buttonClicked:(UIButton *)button
{
    PicViewController *pic = [[PicViewController alloc] init];
    WebViewController *web = [[WebViewController alloc] init];
    for (int i= 0; i < self.picArr.count; i ++) {
        if (button.tag == i + 10) {
            
            if ([[[self.picArr objectAtIndex:i] objectForKey:@"property"] integerValue] == 4) {
                
                pic.myID = [[self.picArr objectAtIndex:i] objectForKey:@"forward_id"];
                [self.navigationController pushViewController:pic animated:YES];
                
                NSLog(@"跳转到编辑 第%d页",i + 1);
            }if([[[self.picArr objectAtIndex:i] objectForKey:@"property"] integerValue] == 9){
                
                web.url = [[self.picArr objectAtIndex:i] objectForKey:@"url"];
                [self.navigationController pushViewController:web animated:YES];
                
                
                NSLog(@"跳转webView 第%d页",i +1);
                
            }
            
            
        }
        
    }
    
    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{
    return self.urlArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *str = @"indentifier";
    GardenCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (!cell) {
        cell = [[[GardenCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str] autorelease];
    }
    
    NSLog(@"========%@",self.urlArr);
    
    workTeam *team = [self.urlArr objectAtIndex:indexPath.row];
    
    cell.minLabel.text = [team.merchant objectForKey:@"name"];
    cell.maxLabel.text = team.title;
    cell.maxLabel.font = [UIFont boldSystemFontOfSize:20];
    cell.minLabel.font = [UIFont boldSystemFontOfSize:13];
    cell.minLabel.textColor = [UIColor grayColor];
    NSString *name = team.cover_path;
    NSURL *url = [NSURL URLWithString:name];
    [cell.gardenView setImageWithURL:url];
    
    
    return cell;
    
}
// cell的点击方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    DetalisViewController *detalisVC = [[DetalisViewController alloc] init];
    
    
    
    
    workTeam *team = [self.urlArr objectAtIndex:indexPath.row];
    
    detalisVC.IDName = team.myID;
    NSLog(@"%@",team.myID);
    [self.navigationController pushViewController:detalisVC animated:YES];
    
}




- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 250;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
